package com.paishen.peiniwan.module.profile;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.paishen.common.album.PhotoAlbumActivity;
import com.paishen.common.album.PhotoWallActivity;
import com.paishen.common.dialog.BottomMenuDialog.BottomMenu;
import com.paishen.common.dialog.LoadingDialog;
import com.paishen.common.dialog.SelectionDialog;
import com.paishen.common.util.BaseUtil;
import com.paishen.peiniwan.App;
import com.paishen.peiniwan.BaseActivity;
import com.paishen.peiniwan.BusEvent;
import com.paishen.peiniwan.C;
import com.paishen.peiniwan.R;
import com.paishen.peiniwan.database.Photo;
import com.paishen.peiniwan.database.PhotoDao;
import com.paishen.peiniwan.database.util.ModelConverter;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.http.HttpResp;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.peiniwan.frame.http.response.HttpRespData;
import com.paishen.peiniwan.frame.widget.PictureLayout;
import com.paishen.common.widget.TitleLayout;
import com.squareup.okhttp.Request;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import de.greenrobot.event.EventBus;
import jp.wasabeef.recyclerview.animators.FadeInAnimator;

public class ProfileAlbumEditActivity extends BaseActivity {

    private static final int RESULT_CODE_GET_PHOTO_BY_ALBUM = 13466;

    private SelectionDialog dlgGetPhoto;
    private PictureLayout layPicture;

    private RecyclerView viewRecycler;
    private PhotoAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isSupportTouchBack = false;
        setContentView(R.layout.activity_profile_album);
        cropImageMode = false;

        layPicture = (PictureLayout) findViewById(R.id.lay_picture);
        List<BottomMenu> bList = new ArrayList<>();
        bList.add(new BottomMenu(getString(R.string.profile_album_delete), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String url = layPicture.getCurrPictureUrl();
                layPicture.hiddenPicture(); // hidden picture will clear url
                layPicture.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        adapter.removeByUrl(ProfileAlbumEditActivity.this, url);
                    }
                }, 600);
            }
        }));
        layPicture.initMenuDialog(bList);

        TitleLayout layTitle = (TitleLayout) findViewById(R.id.lay_title);
        TextView viewFinish = (TextView) LayoutInflater.from(this).inflate(R.layout.layout_title_menu_text, null);
        viewFinish.setText(R.string.profile_album_upload);
        viewFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showGetPhotoDialog();
            }
        });
        layTitle.pushContent(makeBackView(), getString(R.string.main_profile_album), viewFinish, false);

        viewRecycler = (RecyclerView) findViewById(R.id.recycler_album);
        final int verticalCount = 3;
        viewRecycler.setLayoutManager(new GridLayoutManager(this, verticalCount));
        viewRecycler.setAdapter(adapter = new PhotoAdapter());
        viewRecycler.setItemAnimator(new FadeInAnimator());
        viewRecycler.addItemDecoration(new RecyclerView.ItemDecoration() {
            final int spacing = BaseUtil.dip2px(3);

            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.top = spacing;
                outRect.bottom = spacing;
                outRect.right = spacing;
                outRect.left = spacing;
            }
        });

        PhotoDao photoDao = App.i().getCurrDaoSession().getPhotoDao();
        adapter.setLocal(photoDao.queryBuilder().where(PhotoDao.Properties.UserId.eq(App.i().getUser().getId())).orderDesc(PhotoDao.Properties.Id).list());
    }


    private static final class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.ViewHolder> {

        final List<Photo> photoList = new ArrayList<>();

        public List<Photo> queryPhotoList() {
            return photoList;
        }

        public void setLocal(List<Photo> dataList) {
            if (dataList != null && dataList.size() > 0) {
                photoList.clear();
                photoList.addAll(dataList);
                notifyItemRangeChanged(0, photoList.size());
            }
        }

        private void addLocal(List<Photo> dataList) {
            if (dataList != null && dataList.size() > 0) {
                for (Photo p : dataList) {
                    photoList.add(0, p);
                }
                notifyDataSetChanged();
            }
            EventBus.getDefault().post(new BusEvent( BusEvent.ACTION_REFRESH_MAIN_PROFILE_ALBUM));
        }

        public void add(Context context, String data) {
            if (!TextUtils.isEmpty(data)) {
                addAll(context, new File[]{new File(data)});
            }
        }

        public void addAll(Context context, List<String> dataList) {
            if (dataList != null && dataList.size() > 0) {
                File[] files = new File[dataList.size()];
                for (int i = 0; i < dataList.size(); i++) {
                    files[i] = new File(dataList.get(i));
                }
                addAll(context, files);
            }
        }

        private void addAll(Context context, File[] files) {
            if (files != null) {
                final LoadingDialog dlgLoading = new LoadingDialog.Builder(context).create();
                dlgLoading.show();
                PnwHttpManager.User.uploadPhoto(((BaseActivity) context).TAG, files, new PnwOkCallbackAdapter<HttpRespData<List<com.paishen.peiniwan.frame.http.entity.Photo>>>() {
                    @Override
                    public void onResponse(HttpRespData<List<com.paishen.peiniwan.frame.http.entity.Photo>> response, boolean fresh) {
                        super.onResponse(response, fresh);
                        dlgLoading.dismiss();
                        if (response.errcode == C.http.RESULT_SUCCESS) {
                            PhotoDao photoDao = App.i().getCurrDaoSession().getPhotoDao();
                            List<com.paishen.peiniwan.database.Photo> photoList = new ArrayList<>();
                            for (com.paishen.peiniwan.frame.http.entity.Photo p : response.data) {
                                photoList.add(ModelConverter.mergeOrReplace(null, p, App.i().getUser().getId()));
                            }
                            photoDao.insertOrReplaceInTx(photoList);
                            addLocal(photoList);

                        } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                                response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                            BaseUtil.showToast(response.errmsg);
                        }
                    }

                    @Override
                    public void onFailure(Request request, Exception e) {
                        super.onFailure(request, e);
                        dlgLoading.dismiss();
                    }
                });
            }
        }

        public void removeByUrl(Context context, String url) {

            int idx = -1;
            for (int i = 0; i < photoList.size(); i++) {
                if (TextUtils.equals(photoList.get(i).getPhoto_url(), url)) {
                    idx = i;
                    break;
                }
            }
            final int deleteIndex = idx;

            if (deleteIndex >= 0) {
                Photo delete = photoList.get(deleteIndex);
                final Long[] arrDeleted = new Long[]{delete.getId()};
                final LoadingDialog dlgLoading = new LoadingDialog.Builder(context).create();
                dlgLoading.show();
                PnwHttpManager.User.deletePhoto(((BaseActivity) context).TAG, arrDeleted, new PnwOkCallbackAdapter<HttpResp>() {
                    @Override
                    public void onResponse(HttpResp response, boolean fresh) {
                        super.onResponse(response, fresh);
                        dlgLoading.dismiss();
                        if (response.errcode == C.http.RESULT_SUCCESS) {
                            PhotoDao photoDao = App.i().getCurrDaoSession().getPhotoDao();
                            photoDao.deleteByKeyInTx(Arrays.asList(arrDeleted));
                            photoList.remove(deleteIndex);
                            notifyItemRemoved(deleteIndex);
                            EventBus.getDefault().post(new BusEvent( BusEvent.ACTION_REFRESH_MAIN_PROFILE_ALBUM));
                        } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                                response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                            BaseUtil.showToast(response.errmsg);
                        }
                    }

                    @Override
                    public void onFailure(Request request, Exception e) {
                        super.onFailure(request, e);
                        dlgLoading.dismiss();
                    }
                });
            }
        }

        public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            public ViewHolder(View view) {
                super(view);
                view.setOnClickListener(this);
            }

            private ImageView imageView;

            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new BusEvent( BusEvent.ACTION_PROFILE_ALBUM_EDIT_PHOTO_SCAN, v));
            }
        }


        @Override
        public int getItemCount() {
            return photoList.size();
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int mViewType) {
            ImageView viewImage = new ImageView(viewGroup.getContext()) {
                @Override
                protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                    super.onMeasure(widthMeasureSpec, widthMeasureSpec);
                }
            };
            viewImage.setBackgroundColor(0xffcc99cc);
            viewImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
            ViewHolder viewHolder = new ViewHolder(viewImage);
            viewHolder.imageView = viewImage;
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
            final Photo photo = photoList.get(position);
            Glide.with(viewHolder.itemView.getContext()).load(photo.getPhoto_url()).placeholder(R.mipmap.common_pic_s_180).into(viewHolder.imageView);
            viewHolder.itemView.setTag(R.id.frame_picture_url, photo.getPhoto_url());
            // viewHolder.itemData = photo;
        }
    }

    private void showGetPhotoDialog() {
        if (dlgGetPhoto == null) {
            List<SelectionDialog.Menu> menuList = new ArrayList<>();
            menuList.add(new SelectionDialog.Menu(getString(R.string.frame_photo_from_camera), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openCamera();
                    dlgGetPhoto.dismiss();
                }
            }));

            menuList.add(new SelectionDialog.Menu(getString(R.string.frame_photo_from_album), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // openPhotos();

                    Intent intent = new Intent(ProfileAlbumEditActivity.this, PhotoAlbumActivity.class);
                    startActivityForResult(intent, RESULT_CODE_GET_PHOTO_BY_ALBUM);

                    dlgGetPhoto.dismiss();
                }
            }));
            dlgGetPhoto = new SelectionDialog.Builder(this).setMenuList(menuList).create();
        }

        dlgGetPhoto.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RESULT_CODE_GET_PHOTO_BY_ALBUM:
                if (resultCode == RESULT_OK) {
                    List<String> photos = data.getStringArrayListExtra(PhotoWallActivity.EXTRA_SELECTED_PHOTOS);
                    adapter.addAll(this, photos);
                }
                break;
        }
    }

    public void onEventMainThread(com.paishen.peiniwan.BusEvent event) {
        super.onEventMainThread(event);

        if (event.type == BusEvent.TYPE_MAIN_THREAD) {
            switch (event.action) {
                case BusEvent.ACTION_PROFILE_ALBUM_EDIT_PHOTO_SCAN:
                    View v = (View) event.content;
                    // layPicture.showPicture(String.valueOf(v.getTag(R.id.frame_picture_url)), v);
                    String shownUrl = String.valueOf(v.getTag(R.id.frame_picture_url));
                    List<Photo> list = adapter.queryPhotoList();
                    List<String> shownPics = new ArrayList<>();
                    int idx = 0;
                    for (int i = 0; i < list.size(); i++) {
                        String picUrl = list.get(i).getPhoto_url();
                        shownPics.add(picUrl);
                        if (TextUtils.equals(picUrl, shownUrl)) {
                            idx = i;
                        }
                    }
                    if (shownPics.size() > 0) {
                        layPicture.showPicture(shownPics, idx, v);
                    } else {
                        layPicture.showPicture(shownUrl, v);
                    }
                    break;
                case BusEvent.ACTION_PICTURE_QUERY_OUT:
                    adapter.add(this, String.valueOf(event.content));
                    break;
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (View.VISIBLE == layPicture.getVisibility()) {
            layPicture.hiddenPicture();
        } else {
            super.onBackPressed();
        }
    }
}
